<template>
  <div class="app-container">
    <el-container>
      <el-header>
        <h1>代码解读报告生成工具</h1>
      </el-header>
      <el-main>
        <el-card class="upload-card">
          <div class="upload-container">
            <h2>上传代码文件</h2>
            <p>支持上传单个代码文件或ZIP压缩包</p>
            
            <el-upload
              class="upload-area"
              drag
              action="#"
              :http-request="handleUpload"
              :before-upload="beforeUpload"
              :on-change="handleChange"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">
                  支持的文件类型: .py, .java, .js, .html, .css, .php, .c, .cpp, .h, .hpp, .cs, .go, .rb, .rs, .ts, .xml, .json, .md, .sql, .sh, .yml, .yaml 或 .zip 压缩包
                </div>
              </template>
            </el-upload>
            
            <div class="upload-actions">
              <el-button type="primary" @click="submitUpload" :disabled="!fileList.length || loading">
                开始分析
              </el-button>
              <el-button @click="resetUpload" :disabled="!fileList.length || loading">
                重置
              </el-button>
            </div>
          </div>
        </el-card>
        
        <el-card v-if="loading" class="analysis-card">
          <div class="loading-container">
            <el-progress type="circle" :percentage="analysisProgress"></el-progress>
            <p>正在分析代码，请稍候...</p>
          </div>
        </el-card>
        
        <el-card v-if="reportData && !loading" class="report-card">
          <div class="report-header">
            <h2>代码解读报告</h2>
            <div class="report-actions">
              <el-button type="primary" @click="downloadHtmlReport">
                下载HTML报告
              </el-button>
              <el-button @click="downloadMarkdownReport">
                下载Markdown报告
              </el-button>
            </div>
          </div>
          
          <el-tabs v-model="activeTab">
            <el-tab-pane label="项目概览" name="overview">
              <div class="overview-container">
                <div class="overview-stats">
                  <el-statistic title="文件总数" :value="reportData.overview.total_files"></el-statistic>
                  <el-statistic title="支持的语言" :value="Object.keys(reportData.overview.languages).length"></el-statistic>
                </div>
                
                <h3>语言分布</h3>
                <el-table :data="languageTableData" style="width: 100%">
                  <el-table-column prop="language" label="语言"></el-table-column>
                  <el-table-column prop="count" label="文件数"></el-table-column>
                </el-table>
                
                <h3>最大文件</h3>
                <el-table :data="largestFilesData" style="width: 100%">
                  <el-table-column prop="file" label="文件路径"></el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="文件分析" name="files">
              <div class="files-container">
                <el-tree
                  :data="fileTreeData"
                  :props="defaultProps"
                  @node-click="handleNodeClick"
                  default-expand-all
                ></el-tree>
                
                <div v-if="selectedFile" class="file-details">
                  <h3>{{ selectedFile }}</h3>
                  <div class="file-stats">
                    <p><strong>语言:</strong> {{ getFileLanguage(selectedFile) }}</p>
                    <p><strong>大小:</strong> {{ getFileSize(selectedFile) }} 字节</p>
                    <p><strong>行数:</strong> {{ getFileLines(selectedFile) }}</p>
                  </div>
                  
                  <div v-if="getFileImports(selectedFile).length > 0" class="file-imports">
                    <h4>导入</h4>
                    <ul>
                      <li v-for="(imp, index) in getFileImports(selectedFile)" :key="index">
                        {{ imp }}
                      </li>
                    </ul>
                  </div>
                  
                  <div v-if="getFileClasses(selectedFile).length > 0" class="file-classes">
                    <h4>类</h4>
                    <el-table :data="getFileClasses(selectedFile)" style="width: 100%">
                      <el-table-column prop="name" label="名称"></el-table-column>
                      <el-table-column prop="line_number" label="行号"></el-table-column>
                      <el-table-column label="方法数">
                        <template #default="scope">
                          {{ scope.row.methods.length }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  
                  <div v-if="getFileFunctions(selectedFile).length > 0" class="file-functions">
                    <h4>函数</h4>
                    <el-table :data="getFileFunctions(selectedFile)" style="width: 100%">
                      <el-table-column prop="name" label="名称"></el-table-column>
                      <el-table-column prop="line_number" label="行号"></el-table-column>
                      <el-table-column label="参数">
                        <template #default="scope">
                          {{ scope.row.args.join(', ') }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  
                  <div class="file-content">
                    <h4>代码</h4>
                    <pre><code>{{ getFileContent(selectedFile) }}</code></pre>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-main>
      <el-footer>
        <p>代码解读报告生成工具 &copy; 2025</p>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      fileList: [],
      loading: false,
      analysisProgress: 0,
      reportData: null,
      htmlReport: '',
      markdownReport: '',
      activeTab: 'overview',
      selectedFile: null,
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    };
  },
  computed: {
    languageTableData() {
      if (!this.reportData) return [];
      return Object.entries(this.reportData.overview.languages).map(([language, count]) => ({
        language,
        count
      }));
    },
    largestFilesData() {
      if (!this.reportData) return [];
      return this.reportData.overview.largest_files.map(file => ({
        file
      }));
    },
    fileTreeData() {
      if (!this.reportData) return [];
      
      // 构建文件树
      const root = { label: '项目根目录', children: [] };
      
      for (const filePath in this.reportData.files) {
        const parts = filePath.split('/');
        let currentNode = root;
        
        for (let i = 0; i < parts.length; i++) {
          const part = parts[i];
          
          // 最后一部分是文件名
          if (i === parts.length - 1) {
            currentNode.children.push({
              label: part,
              filePath: filePath,
              isLeaf: true
            });
          } else {
            // 查找或创建目录节点
            let found = false;
            for (const child of currentNode.children) {
              if (child.label === part && !child.isLeaf) {
                currentNode = child;
                found = true;
                break;
              }
            }
            
            if (!found) {
              const newNode = {
                label: part,
                children: [],
                isLeaf: false
              };
              currentNode.children.push(newNode);
              currentNode = newNode;
            }
          }
        }
      }
      
      return root.children;
    }
  },
  methods: {
    beforeUpload(file) {
      const validExtensions = [
        '.py', '.java', '.js', '.html', '.css', '.php', '.c', '.cpp', '.h', '.hpp',
        '.cs', '.go', '.rb', '.rs', '.ts', '.xml', '.json', '.md', '.sql', '.sh',
        '.yml', '.yaml', '.zip'
      ];
      
      const extension = '.' + file.name.split('.').pop().toLowerCase();
      
      if (!validExtensions.includes(extension)) {
        this.$message.error('不支持的文件类型！');
        return false;
      }
      
      return true;
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1); // 只保留最后一个文件
    },
    resetUpload() {
      this.fileList = [];
      this.reportData = null;
      this.htmlReport = '';
      this.markdownReport = '';
      this.selectedFile = null;
    },
    submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择文件');
        return;
      }
      
      this.loading = true;
      this.analysisProgress = 0;
      
      // 模拟进度
      const progressInterval = setInterval(() => {
        if (this.analysisProgress < 90) {
          this.analysisProgress += 10;
        }
      }, 500);
      
      this.handleUpload(this.fileList[0]);
      
      // 清除进度条定时器
      setTimeout(() => {
        clearInterval(progressInterval);
      }, 10000);
    },
    handleUpload(file) {
      const formData = new FormData();
      formData.append('file', file.raw);
      
      this.$axios.post('/analyze', formData)
        .then(response => {
          this.analysisProgress = 100;
          this.reportData = response.data.analysis_results;
          this.htmlReport = response.data.html_report;
          this.markdownReport = response.data.markdown_report;
          this.loading = false;
          this.$message.success('代码分析完成');
        })
        .catch(error => {
          this.loading = false;
          this.$message.error('分析失败: ' + (error.response?.data?.error || error.message));
        });
    },
    downloadHtmlReport() {
      if (!this.htmlReport) return;
      
      const blob = new Blob([this.htmlReport], { type: 'text/html' });
      this.downloadBlob(blob, 'code_analysis_report.html');
    },
    downloadMarkdownReport() {
      if (!this.markdownReport) return;
      
      const blob = new Blob([this.markdownReport], { type: 'text/markdown' });
      this.downloadBlob(blob, 'code_analysis_report.md');
    },
    downloadBlob(blob, filename) {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = filename;
      link.click();
      URL.revokeObjectURL(link.href);
    },
    handleNodeClick(data) {
      if (data.isLeaf) {
        this.selectedFile = data.filePath;
      }
    },
    getFileLanguage(filePath) {
      return this.reportData.files[filePath]?.language || '未知';
    },
    getFileSize(filePath) {
      return this.reportData.files[filePath]?.size || 0;
    },
    getFileLines(filePath) {
      return this.reportData.files[filePath]?.lines || 0;
    },
    getFileImports(filePath) {
      return this.reportData.files[filePath]?.imports || [];
    },
    getFileClasses(filePath) {
      return this.reportData.files[filePath]?.classes || [];
    },
    getFileFunctions(filePath) {
      return this.reportData.files[filePath]?.functions || [];
    },
    getFileContent(filePath) {
      return this.reportData.files[filePath]?.content || '';
    }
  }
};
</script>

<style>
.app-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  line-height: 60px;
}

.el-main {
  padding: 20px;
  background-color: #f5f7fa;
}

.el-footer {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.upload-card, .analysis-card, .report-card {
  margin-bottom: 20px;
}

.upload-container {
  text-align: center;
  padding: 20px;
}

.upload-area {
  margin: 20px 0;
}

.upload-actions {
  margin-top: 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.overview-stats {
  display: flex;
  gap: 40px;
  margin-bottom: 30px;
}

.files-container {
  display: flex;
  gap: 20px;
}

.files-container .el-tree {
  width: 300px;
  overflow: auto;
  border-right: 1px solid #EBEEF5;
  padding-right: 10px;
}

.file-details {
  flex: 1;
  padding-left: 20px;
}

.file-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.file-imports, .file-classes, .file-functions, .file-content {
  margin-bottom: 20px;
}

.file-content pre {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow: auto;
  max-height: 500px;
}
</style>
